//
//  MDHWKWebViewController.m
//  MDHPT
//
//  Created by 高得华 on 2019/5/28.
//  Copyright © 2019年 高得华. All rights reserved.
//

#import "MDHWKWebViewController.h"
#import "NSString+XHLaunchAd.h"

#if __has_include("MDHPT/MDHPT-Swift.h")
#import "MDHPT/MDHPT-Swift.h"
#else
#import "MDHPT-Swift.h"
#endif

///加载网址请求的类型
typedef NS_ENUM(NSInteger, MMWPTWkWebLoadType) {
    loadWebURLString = 0,
    loadWebHTMLString,
    POSTWebURLString,
};

static void *WkwebBrowserContext = &WkwebBrowserContext;

@interface MDHWKWebViewController ()
<
WKNavigationDelegate,
WKUIDelegate,
WKScriptMessageHandler
>

///WebView网页加载器
@property (nonatomic, strong, readwrite) WKWebView * wkWebView;
///设置加载进度条
@property (nonatomic, strong, readwrite) UIProgressView * progressView;
///返回按钮
@property (nonatomic, strong, readwrite) UIBarButtonItem * customBackBarItem;
///关闭按钮
@property (nonatomic, strong, readwrite) UIBarButtonItem * closeButtonItem;
///保存请求链接
@property (nonatomic, strong, readwrite) NSMutableArray * snapShotsArray;

///仅当第一次的时候加载本地JS
@property (nonatomic, assign) BOOL needLoadJSPOST;
///网页加载的类型
@property (nonatomic, assign) MMWPTWkWebLoadType loadType;
///保存的网址链接
@property (nonatomic, copy) NSString *URLString;
///保存POST请求体
@property (nonatomic, copy) NSString *postData;

///下拉刷新
@property (nonatomic, strong, readwrite) MJRefreshNormalHeader * refreshHeader;
///刷新控件按钮
@property (nonatomic, strong, readwrite) UIBarButtonItem * barBtnItemRefresh;
///右侧的文字按钮
@property (nonatomic, strong, readwrite) MMWDHButton * buttonWWords;
///右侧控件按钮
@property (nonatomic, strong, readwrite) UIBarButtonItem * barBtnItemRight;

///ViewModel
@property (nonatomic, strong, readwrite) MDHWebViewModel * viewModel;

@end

@implementation MDHWKWebViewController

@synthesize viewModel = _viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    ///设置标题 [GEdwardInfoController sharedInstance].CFBundleDisplayName
    [self setNavigationItemTitle:@"跳转中..."];
    
    //if (self.isNoSystem) {///非系统
    //    [self ShowWebViewPageOne];
    //}else{
        ///添加到主控制器上
        [self.view addSubview:self.wkWebView];
        ///添加进度条
        [self.view addSubview:self.progressView];
    //}
    
    [self.wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.contentInset);
    }];
    
    ///加载web页面
    [self webViewloadURLType];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.viewModel.prefersNavigationBarHidden) {
        self.navigationController.navigationBarHidden = true;
    }else{
        self.navigationController.navigationBarHidden = false;
    }
    if (self.blockViewWillAppear != nil) {
        self.blockViewWillAppear();
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (self.viewModel.prefersNavigationBarHidden) {
        //创建一个高20的假状态栏
        UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, kMMWPTFC().kSafeAreaTop)];
        //设置成绿色
        statusBarView.backgroundColor=[UIColor whiteColor];
        // 添加到 navigationBar 上
        [self.view addSubview:statusBarView];
        self.progressView.frame = CGRectMake(0, kMMWPTFC().kSafeAreaTop, self.view.bounds.size.width, 5);
    }else{
        self.progressView.frame = CGRectMake(0, kMMWPTFC().kTranslucentTop, self.view.bounds.size.width, 5);
    }
    [self.wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.contentInset);
    }];

    /// CoderMikeHe: 适配 iPhone X + iOS 11，去掉安全区域
    if (@available(iOS 11.0, *)) {
        //[self.viewModel adjustsScrollViewInsets_Never:self.wkWebView.scrollView];
    }
    if (self.blockViewDidLayoutSubviews != nil) {
        self.blockViewDidLayoutSubviews();
    }
}

- (UIEdgeInsets)contentInset {
    if (self.viewModel.prefersNavigationBarHidden) {
        return UIEdgeInsetsMake(0, 0, kMMWPTFC().kSafeAreaBottom, 0);
    }
    return UIEdgeInsetsMake(kMMWPTFC().kNavSafeArea, 0, kMMWPTFC().kSafeAreaBottom, 0);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//MARK: - ================ 加载方式
///重新加载
- (void)roadLoadClicked {
    [self.wkWebView reload];
}

- (void)webViewloadURLType {
    switch (self.loadType) {
        case loadWebURLString:{
            //创建一个NSURLRequest 的对象
            NSURLRequest * Request_zsj = [NSURLRequest requestWithURL:[NSURL URLWithString:self.URLString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
            //加载网页
            [self.wkWebView loadRequest:Request_zsj];
            break;
        }
        case loadWebHTMLString:{
            [self loadHostPathURL:self.URLString];
            break;
        }
        case POSTWebURLString:{
            // JS发送POST的Flag，为真的时候会调用JS的POST方法
            self.needLoadJSPOST = YES;
            //POST使用预先加载本地JS方法的html实现，请确认WKJSPOST存在
            [self loadHostPathURL:@"WKJSPOST"];
            break;
        }
    }
}

- (void)loadHostPathURL:(NSString *)url {
    //获取JS所在的路径
    NSString *path = [[NSBundle mainBundle] pathForResource:url ofType:@"html"];
    //获得html内容
    NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //加载js
    [self.wkWebView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
}

// 调用JS发送POST请求
- (void)postRequestWithJS {
    // 拼装成调用JavaScript的字符串
    NSString *jscript = [NSString stringWithFormat:@"post('%@', %@);", self.URLString, self.postData];
    // 调用JS代码
    [self.wkWebView evaluateJavaScript:jscript completionHandler:^(id object, NSError * _Nullable error) {
        if (error) {
            DTLog(@"%@",error.debugDescription);
        }
    }];
}

- (void)loadWebURLSring:(NSString *)string {
    self.URLString = string;
    self.loadType = loadWebURLString;
}

- (void)loadWebHTMLSring:(NSString *)string {
    self.URLString = string;
    self.loadType = loadWebHTMLString;
}

- (void)POSTWebURLSring:(NSString *)string postData:(NSString *)postData{
    self.URLString = string;
    self.postData = postData;
    self.loadType = POSTWebURLString;
}
- (void)setURLString:(NSString *)URLString {
    URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    _URLString = URLString;
}



//MARK: - ==== 私有方法
/**
 url是否是跳转APP类型的
 
 @param URL as
 @return BOOL
 */
- (BOOL)isExternalAppWithURL:(NSURL *)URL {
    if (URL == nil) {
        return false;
    }
    NSSet * validSchemes = [NSSet setWithArray:@[@"http", @"https", @"file"]];
    return ![validSchemes containsObject:URL.scheme];
}
///设置标题
- (void)setNavigationItemTitle:(NSString *)title {
    if (title.length <= 0) {
        title = @"跳转中...";//[GEdwardInfoController sharedInstance].CFBundleDisplayName;
    }
    self.title = title;
}
///关闭按钮的点击响应事件
- (void)closeItemClicked {
    ///销毁视图
    //[self deallocView];
    [self.navigationController popViewControllerAnimated: true];
}
///返回按钮的点击响应事件
- (void)customBackItemClicked {
    if (self.wkWebView.goBack) {
        [self.wkWebView goBack];
    }else{
        [self closeItemClicked];
    }
}

///更新导航栏上的按钮
- (void)updateNavigationItems {
    if (self.wkWebView.canGoBack) {
        UIBarButtonItem *spaceButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        spaceButtonItem.width = -6.5;
        
        [self.navigationItem setLeftBarButtonItems:@[spaceButtonItem,self.customBackBarItem,self.closeButtonItem] animated:NO];
    }else{
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        [self.navigationItem setLeftBarButtonItems:@[self.customBackBarItem]];
    }
    
    ///添加右边按钮
    //self.navigationItem.rightBarButtonItem = self.viewStyle == 4 ? self.barBtnItemRight:self.barBtnItemRefresh;
}
///请求链接处理
- (void)pushCurrentSnapshotViewWithRequest:(NSURLRequest*)request {
    //    NSLog(@"push with request %@",request);
    NSURLRequest* lastRequest = (NSURLRequest*)[[self.snapShotsArray lastObject] objectForKey:@"request"];
    //如果url是很奇怪的就不push
    if ([request.URL.absoluteString isEqualToString:@"about:blank"]) {
        //NSLog(@"about blank!! return");
        return;
    }
    //如果url一样就不进行push
    if ([lastRequest.URL.absoluteString isEqualToString:request.URL.absoluteString]) {
        return;
    }
    UIView * currentSnapShotView = [self.wkWebView snapshotViewAfterScreenUpdates:YES];
    [self.snapShotsArray addObject:
     @{@"request":request,@"snapShotView":currentSnapShotView}];
}


#pragma mark ================ WKNavigationDelegate ================
///开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    BOOL isOk = [[MDHWKWebViewManager share] isMiaomiaoWithUrl:webView.URL.absoluteString];
    if (isOk) {
        //开始加载的时候，让加载进度条显示
        self.progressView.hidden = false;
    }
}

///这个是网页加载完成，导航的变化
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    /*
     主意：这个方法是当网页的内容全部显示（网页内的所有图片必须都正常显示）的时候调用（不是出现的时候就调用），，否则不显示，或则部分显示时这个方法就不调用。
     */
    // 判断是否需要加载（仅在第一次加载）
    if (self.needLoadJSPOST) {
        // 调用使用JS发送POST请求的方法
        [self postRequestWithJS];
        // 将Flag置为NO（后面就不需要加载了）
        self.needLoadJSPOST = NO;
    }
    // 获取加载网页的标题
    NSString * title = self.wkWebView.title;
    [self setNavigationItemTitle:title];
    ///通知刷新
    [self.refreshHeader endRefreshing];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateNavigationItems];
}

///内容返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
}

///服务器请求跳转的时候调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    
}

///服务器开始请求的时候调用
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL * URL = navigationAction.request.URL;
    if (![[MDHWKWebViewManager share] pushWithUrl:URL.absoluteString]) {
        /////允许跳转
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    if ([self isExternalAppWithURL:URL]) {
        ///以 itms-apps://或https:// 开头的应用详情页链接，跳转到AppStore
        ///以itms:// 开头的应用详情页连接，跳转到 iTunes Store，打开的仍然是应用的下载页
        NSString * scheme = URL.scheme;///itms-apps://
        NSString * absoluteString = [URL.absoluteString stringByReplacingOccurrencesOfString:scheme withString:@""];
        absoluteString = [@"itms-apps" stringByAppendingString:absoluteString];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:absoluteString]];
        //decisionHandler(WKNavigationActionPolicyAllow);
    }else{
        ///跳转的网址
        NSString * absoluteString = URL.absoluteString;
        DTLog(@"跳转网址: %@",absoluteString);
        
        ///是否是 商品的URL
        //BOOL isShop = [absoluteString hasPrefix:[MMWPTUserInforManager share].ui.shop_url];
        //self.viewStyle = isShop ? 4:-1;
        
        switch (navigationAction.navigationType) {
            case WKNavigationTypeLinkActivated: {
                [self pushCurrentSnapshotViewWithRequest:navigationAction.request];
                break;
            }
            case WKNavigationTypeFormSubmitted: {
                [self pushCurrentSnapshotViewWithRequest:navigationAction.request];
                break;
            }
            case WKNavigationTypeBackForward: {
                break;
            }
            case WKNavigationTypeReload: {
                break;
            }
            case WKNavigationTypeFormResubmitted: {
                break;
            }
            case WKNavigationTypeOther: {
                [self pushCurrentSnapshotViewWithRequest:navigationAction.request];
                break;
            }
            default: {
                break;
            }
        }
        [self updateNavigationItems];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    NSString * absoluteString = navigationResponse.response.URL.absoluteString;
    if ([[MDHWKWebViewManager share] isMiaomiaoWithUrl:absoluteString]) {
        ///不允许跳转
        decisionHandler(WKNavigationResponsePolicyCancel);
    }else{
        decisionHandler(WKNavigationResponsePolicyAllow);
    }
}

// 内容加载失败时候调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    DTLog(@"页面加载超时");
    //ShowHUDMesHidden(error.debugDescription, self.view);
    ///通知刷新
    [self.refreshHeader endRefreshing];
}

///跳转失败的时候调用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    //ShowHUDMesHidden(error.debugDescription, self.view);
    [self.refreshHeader endRefreshing];
}

///进度条
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    
}


#pragma mark ================ WKUIDelegate ================
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    WKFrameInfo * frameInfo = navigationAction.targetFrame;
    if (frameInfo && frameInfo.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return [WKWebView new];
}
/// 获取js 里面的提示
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    /*UIAlertController *alert = [UIAlertController alertControllerWithTitle:kLocalizedString(@"提示", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
     [alert addAction:[UIAlertAction actionWithTitle:kLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
     completionHandler();
     }]];
     
     [self presentViewController:alert animated:YES completion:NULL];*/
}

/// js 信息的交流
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    /*UIAlertController *alert = [UIAlertController alertControllerWithTitle:kLocalizedString(@"提示", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
     [alert addAction:[UIAlertAction actionWithTitle:kLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
     completionHandler(YES);
     }]];
     [alert addAction:[UIAlertAction actionWithTitle:kLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
     completionHandler(NO);
     }]];
     [self presentViewController:alert animated:YES completion:NULL];*/
    completionHandler(true);
}

/// 交互。可输入的文本。
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    /*UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS调用输入框" preferredStyle:UIAlertControllerStyleAlert];
     [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
     textField.textColor = [UIColor redColor];
     }];
     [alert addAction:[UIAlertAction actionWithTitle:kLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
     completionHandler([[alert.textFields lastObject] text]);
     }]];
     
     [self presentViewController:alert animated:YES completion:NULL];*/
}



#pragma mark ================ WKScriptMessageHandler ================
///拦截执行网页中的JS方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
}


///KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
        
        // Once complete, fade out UIProgressView
        if(self.wkWebView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

//MARK: - ===== 懒加载 ===== -
///进度条
- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        // 设置进度条的色彩
        [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
        _progressView.progressTintColor = [UIColor greenColor];
    }
    return _progressView;
}
///WebView网页加载器
- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        ///设置网页的配置文件
        WKWebViewConfiguration * configuration = [WKWebViewConfiguration new];
        ///允许视频播放
        if (@available(iOS 9.0, *)) {
            configuration.allowsAirPlayForMediaPlayback = true;
        } else {
            // Fallback on earlier versions
        }
        ///允许在线播放
        configuration.allowsInlineMediaPlayback = true;
        // 允许可以与网页交互，选择视图
        configuration.selectionGranularity = true;
        configuration.mediaPlaybackAllowsAirPlay = true;
        configuration.mediaPlaybackRequiresUserAction = false;
        // web内容处理池
        configuration.processPool = [[WKProcessPool alloc] init];
        //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
        WKUserContentController * UserContentController = [[WKUserContentController alloc]init];
        // 是否支持记忆读取
        configuration.suppressesIncrementalRendering = true;
        // 允许用户更改网页的设置
        configuration.userContentController = UserContentController;
        CGRect rect = self.view.bounds;
        rect.size.height -= kMMWPTFC().kSafeAreaBottom;
        _wkWebView = [[WKWebView alloc] initWithFrame:rect configuration:configuration];
        _wkWebView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];
        // 设置代理
        _wkWebView.navigationDelegate = self;
        _wkWebView.UIDelegate = self;
        //kvo 添加进度监控
        [_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkwebBrowserContext];
        //开启手势触摸
        _wkWebView.allowsBackForwardNavigationGestures = YES;
        // 设置 可以前进 和 后退
        //适应你设定的尺寸
        [_wkWebView sizeToFit];
        ///添加刷新控件
        _wkWebView.scrollView.mj_header = self.refreshHeader;
    }
    return _wkWebView;
}
///关闭按钮
- (UIBarButtonItem*)closeButtonItem {
    if (!_closeButtonItem) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"关闭" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];///self.navigationController.navigationBar.tintColor
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];///[self.navigationController.navigationBar.tintColor colorWithAlphaComponent:0.5]
        [btn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [btn sizeToFit];
        //设置内容偏移量
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, -22, 0, 0);
        [btn addTarget:self action:@selector(closeItemClicked) forControlEvents:UIControlEventTouchUpInside];
        _closeButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    return _closeButtonItem;
}
///返回按钮
- (UIBarButtonItem*)customBackBarItem {
    if (!_customBackBarItem) {
        UIImage* backItemImage = [UIImage imageNamed:kCommonNavButtonBack];//[[UIImage imageNamed:@"common_nav_btn_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        UIImage* backItemHlImage = [UIImage imageNamed:kCommonNavButtonBack];//[[UIImage imageNamed:@"common_nav_btn_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setTitle:@"返回" forState:UIControlStateNormal];
        [backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];///self.navigationController.navigationBar.tintColor
        [backButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];///[self.navigationController.navigationBar.tintColor colorWithAlphaComponent:0.5]
        [backButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [backButton setImage:backItemImage forState:UIControlStateNormal];
        [backButton setImage:backItemHlImage forState:UIControlStateHighlighted];
        [backButton sizeToFit];
        backButton.contentEdgeInsets = UIEdgeInsetsMake(0, -22, 0, 0);
        //设置内容偏移量
        //backButton.contentEdgeInsets = UIEdgeInsetsMake(1.0, -6, 0, 0);
        [backButton addTarget:self action:@selector(customBackItemClicked) forControlEvents:UIControlEventTouchUpInside];
        _customBackBarItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    }
    return _customBackBarItem;
}
///刷新控件
- (UIBarButtonItem *)barBtnItemRefresh {
    if (!_barBtnItemRefresh) {
        UIImage* backItemImage = [UIImage imageNamed:@"common_nav_btn_refresh"];//[[UIImage imageNamed:@"common_nav_btn_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        UIImage* backItemHlImage = [UIImage imageNamed:@"common_nav_btn_refresh"];//[[UIImage imageNamed:@"common_nav_btn_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:backItemImage forState:UIControlStateNormal];
        [btn setImage:backItemHlImage forState:UIControlStateHighlighted];
        [btn sizeToFit];
        //设置内容偏移量
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -22);
        [btn addTarget:self action:@selector(roadLoadClicked) forControlEvents:UIControlEventTouchUpInside];
        _barBtnItemRefresh = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    return _barBtnItemRefresh;
}
///文字 按钮
- (MMWDHButton *)buttonWWords {
    if (!_buttonWWords) {
        __weak typeof(self) weakSelf = self;
        _buttonWWords = [MDHSwiftHeader navTitleWithTitle:@"" color:nil font:nil left:false];
        [[[_buttonWWords rac_signalForControlEvents:UIControlEventTouchUpInside] deliverOnMainThread] subscribeNext:^(id x) {
            switch (weakSelf.viewModel.viewStyle) {
                case 4:///交易记录
                {
                    //NSString * url = [MMWPTUserInforManager share].ui.transaction_url;
                    //[[AppDelegate sharedAppDelegate] pushToH5Vc:url title:@"交易记录" data:nil];
                }
                    break;
                default:
                    break;
            }
        }];
    }
    return _buttonWWords;
}

- (UIBarButtonItem *)barBtnItemRight {
    if (!_barBtnItemRight) {
        _barBtnItemRight = [[UIBarButtonItem alloc] initWithCustomView:self.buttonWWords];
    }
    return _barBtnItemRight;
}

///保存请求的连接
- (NSMutableArray *)snapShotsArray {
    if (!_snapShotsArray) {
        _snapShotsArray = [NSMutableArray array];
    }
    return _snapShotsArray;
}

///下拉刷新
- (MJRefreshNormalHeader *)refreshHeader {
    if (!_refreshHeader) {
        __weak typeof(self) weakSelf = self;
        _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf roadLoadClicked];
        }];
    }
    return _refreshHeader;
}

///注意，观察的移除
- (void)dealloc {
    [self deallocView];
}

///销毁数据
- (void)deallocView {
    if (self.wkWebView) {
        [self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
        [self.wkWebView stopLoading];
        [self.wkWebView setNavigationDelegate:nil];
        [self.wkWebView setUIDelegate:nil];
    }
    self.progressView = nil;
    self.refreshHeader = nil;
    self.snapShotsArray = nil;
    self.buttonWWords = nil;
}

@end
